import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Button, Card, DatePicker, Icon, message, Radio, Select, Table } from 'antd';

import EchartsLine from '@/components/Dashboard/EchartsLine';
import { PageLoading } from '@ant-design/pro-layout';
// import { ENERGYCATEGORY_PRICE } from '@/utils/constants';
import memoryUtils from '@/utils/memoryUtils';

const { RangePicker } = DatePicker;
const { Option } = Select;

class trend extends Component {

  static defaultProps = {
    searchParamsValue: [],
    energyCategoryType: ''
  }

  constructor(props) {
    super(props);
    this.DATE_FORMAT = ['YYYY-MM-DD', 'YYYY-MM', 'YYYY'];
    this.DATE_MODE = [['date', 'date'], ['month', 'month'], ['year', 'year']];
    this.state = {
      showType: 'line',
      // computeType: Object.keys(memoryUtils.ENERGYCATEGORY_PRICE)[0],
      computeType: props.computeTypes ? props.computeTypes[0].value : '',
      searchParamsValueStr: props.searchParamsValue?props.searchParamsValue.join('|||'):'',
      dateValue:[],
      period: 0,
      dateRangeShow: false,
    };
  }

  searchData = () => {
    const { searchParamsValueStr, dateValue, period, computeType  } = this.state;
    if (!searchParamsValueStr || searchParamsValueStr.trim() === '') {
      message.warning('查询参数不能为空');
      return false;
    } else if (!dateValue || dateValue.length < 2) {
      message.warning('请选择查询日期');
      return false;
    } else {
      const payload = { h:searchParamsValueStr, t:1, p:period, startTime: dateValue[0].format(this.DATE_FORMAT[period]), endTime: dateValue[1].format(this.DATE_FORMAT[period]) };
      const energyPrice = memoryUtils.ENERGYCATEGORY_PRICE[computeType]?memoryUtils.ENERGYCATEGORY_PRICE[computeType]:'[{"s":0,"e":-1,"c":1,"p":1}]';
      payload.price = energyPrice;
      this.props.dispatch({ type: 'energyStatistics/fetchProportionTrend', payload });
    }
  };

  createEchartsData = (lists = []) => {
    let xDatas = [], yDatasN = [];
    lists.forEach((list) => {
      const yData = {};
      list.forEach((data) => {
        xDatas.push(data.time);
        yData[data.time] = (100*data.value).toFixed(2);//[data.time, (100*data.value).toFixed(2)];
      });
      yDatasN.push(yData);
    });
    xDatas = [...new Set(xDatas)];
    xDatas.sort((a, b) => (new Date(a) - new Date(b)));
    const yDatas = [];
    yDatasN.forEach((list)=>{
      const yData = [];
      xDatas.forEach((xData)=>{
        if(list[xData]) {
          yData.push(list[xData]);
        }
      });
      yDatas.push(yData);
    });
    return { xDatas, yDatas };
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.searchParamsValue !== this.props.searchParamsValue) {
      this.setState({ searchParamsValueStr: nextProps.searchParamsValue?nextProps.searchParamsValue.join('|||'):'' });
    }
    // if(nextProps.energyCategoryType !== this.props.energyCategoryType) {
    //   this.setState({ energyPrice: ENERGYCATEGORY_PRICE[nextProps.$handle]?memoryUtils.ENERGYCATEGORY_PRICE[nextProps.$handle]:'[]' });
    // }
    if (JSON.stringify(nextProps.names) !== JSON.stringify(this.props.names) || JSON.stringify(nextProps.lists) !== JSON.stringify(this.props.lists)) {
      const { names, lists } = nextProps;
      const { xDatas, yDatas } = this.createEchartsData(lists);
      if ((this.state.showType === 'line' || this.state.showType === 'bar') && this.echartsLine) {
        this.echartsLine.updateChart(names, yDatas, this.state.showType, xDatas);
      }
    }
  }

  componentWillUnmount() {
    this.props.dispatch({ type: 'energyStatistics/clearAll' });
  }

  handleComputeTypeChange = (e)=>{
    this.setState({
      computeType: e.target.value
    }, ()=>{
      if(this.props.lists && this.props.lists.length > 0) {
        this.searchData();
      }
    });
  }

  render() {
    const { computeTypes, names, lists, tDatas, loading } = this.props;
    if(loading) {
      return <PageLoading/>;
    }
    const { showType, computeType, dateValue, period, dateRangeShow } = this.state;
    const title = (
      <span className={'space8'}>
        <Radio.Group name={'computeType'} value={computeType} onChange={this.handleComputeTypeChange}>
          {computeTypes.map(item=>(<Radio value={item.value}>{item.label}</Radio>))}
        </Radio.Group>
        <RangePicker
          allowClear={false}
          showTime={false}
          open={dateRangeShow}
          mode={this.DATE_MODE[period]}
          format={this.DATE_FORMAT[period]}
          value={dateValue}
          placeholder={['开始时间', '结束时间']}
          onChange={value=> this.setState({ dateValue: value})}
          onPanelChange={value=> this.setState({ dateValue: value, dateRangeShow: false})}
          onOpenChange={value=> this.setState({ dateRangeShow: value})}
        />
        <Select value={period} onChange={value=> this.setState({ period: value})}>
          <Option value={0}>日</Option>
          <Option value={1}>月</Option>
          <Option value={2}>年</Option>
        </Select>
      </span>
    );
    const extra = (
      <span className={'space8'}>
        <Radio.Group name={'showType'} value={showType}
                     buttonStyle='solid'
                     onChange={event => this.setState({ showType: event.target.value })}>
          <Radio.Button value='line'><Icon type='line-chart'/></Radio.Button>
          <Radio.Button value='table'><Icon type='table'/></Radio.Button>
          <Radio.Button value='bar'><Icon type='bar-chart'/></Radio.Button>
        </Radio.Group>
        <Button type='primary' onClick={() => this.searchData()}>
          <Icon type={'search'}/>查询
        </Button>
        <div style={{ display: 'none' }}>
          <form action='' id='exportForm' target='exportIFrame' method='post' accept-charset='utf-8'></form>
          <iframe name='exportIFrame' id='exportIFrame'></iframe>
        </div>
      </span>
    );
    let dom = <></>;
    const { xDatas, yDatas } = this.createEchartsData(lists, names);
    if (showType === 'table') {
      const columns = [{
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
      }, {
        title: '采集时间',
        dataIndex: 'time',
        key: 'time',
      }];
      names.forEach((column) => {
        columns.push({
          title: column,
          dataIndex: column,
          key: column,
        });
      });
      dom = (<Table
        title={() => '查询结果'}
        className={'common-table-wrapper'}
        columns={columns}
        dataSource={tDatas}
        rowKey='_id'
        loading={loading}
        pagination={{
          total: tDatas.length,
          pageSize: tDatas.length,
          current: 1
        }}
        scroll={{ y: 500 }}
      />);

    } else {
      dom = (<EchartsLine ref={(e)=> {
        this.echartsLine = e;
      }} title='查询结果' legends={names} xDatas={xDatas} datas={yDatas} showType={showType} bArea={true} bPercent={true} bDashboard={false}/>);
    }
    return (
      <Card title={title} extra={extra} style={{ height: '100%' }} bodyStyle={{ height: '80%' }}>{dom}</Card>
    );
  }
}

trend.propTypes = {
  searchParamsValue: PropTypes.array,
  energyCategoryType: PropTypes.string,
  computeTypes: PropTypes.array.isRequired
};

export default connect(({ energyStatistics, loading }) => ({
  ...energyStatistics,
  loading: loading.effects['energyStatistics/fetchProportionTrend'],
}))(trend);
